<template>
  <div class="channelConfig">
    <div class="teamConfigBtn">
      <div class="searchBox"></div>
      <Button type="primary" @click="addChannel" v-if="unlocking('0102010401')">新增配置</Button>
    </div>
    <div class="tab">
      <Table ref="TableHeight" :max-height="onresizeHeight" :columns="columns" :data="data"
        border></Table>
    </div>
    <page :pageData="pageData" @pageOnChangeFun="pageOnChangeFun"
      @pageOnPageSizeChangeFun="pageOnPageSizeChangeFun"></page>
    <Modal v-model="modal" title="客户渠道" @on-cancel="modalCancel">
      <div class="modalCon">
        <span><em>*</em> 渠道分类：</span>
        <div class="modalConSel">
          <Select v-model="channelRelated.channelType" placeholder="请选择渠道分类"
            :disabled="!create || seeChannelFlag" @on-change="channelTypeChange">
            <Option v-for="(item, index) in channelTypeData" :key="index" :value="item.key"
              :label="item.value">
            </Option>
          </Select>
        </div>
      </div>
      <div class="modalCon">
        <span><em>*</em> 渠道名称：</span>
        <div class="modalConSel">
          <Input v-model="channelRelated.channelName" :disabled="!create || seeChannelFlag"
            placeholder="输入渠道名称（最多输入20个字符）" maxlength="20" />
        </div>
      </div>
      <div class="modalCon" v-if="formFlag">
        <span><em>*</em> 合作类型：</span>
        <div class="modalConSel">
          <Select v-model="channelRelated.cooperationType"
            :disabled=" seeChannelFlag || (!create && iscooperationType)" placeholder="请选择合作类型"
            @on-change="cooperationTypeChange">
            <Option v-for="(item, index) in cooperationTypeList" :key="index" :value="item.key"
              :label="item.value">
            </Option>
          </Select>
        </div>
      </div>
      <div class="modalCon" v-if="formFlag">
        <span><em v-if="formFlag2">*</em> 合作开始日期：</span>
        <div class="modalConSel">
          <DatePicker type="date" :disabled="seeChannelFlag" style="width: 300px"
            placeholder="请选择合作开始日期" v-model="channelRelated.startDate" format="yyyy-MM-dd"
            @on-change="startDateChange">
          </DatePicker>
        </div>
      </div>
      <div class="modalCon" v-if="formFlag">
        <span><em v-if="formFlag2">*</em> 合作结束日期：</span>
        <div class="modalConSel">
          <DatePicker type="date" :disabled="seeChannelFlag" style="width: 300px"
            placeholder="请选择合作结束日期" v-model="channelRelated.endDate" format="yyyy-MM-dd"
            @on-change="endDateChange"></DatePicker>
        </div>
      </div>
      <div class="tip" v-if="formFlag">
        {{
          formFlag2
            ? "该渠道仅在合作时间范围内可选"
            : "该渠道仅在合作时间范围内可选，不填为永久"
        }}
      </div>

      <div class="modalCon" v-if="formFlag && formFlag2">
        <span><em>*</em> 渠道费用：</span>
        <div class="modalConSel channelCostType">
          <Select v-model="channelRelated.channelCostType" v-if="!seeChannelFlag"
            placeholder="渠道费用类型" @on-change="channelCostTypeChange">
            <Option v-for="(item, index) in channelCostTypeData" :key="index" :value="item.key"
              :label="item.value">
            </Option>
          </Select>
          <InputNumber type="number" style="width: 200px" :min="0" :disabled="seeChannelFlag"
            v-model="channelRelated.channelCost" @on-change="checkChannelCost" :placeholder="
              channelRelated.channelCostType == 1 ? '请输入金额' : '请输入比例'
            ">
          </InputNumber>
          <span>{{ channelRelated.channelCostType == 1 ? "元" : "%" }}</span>
        </div>
      </div>
      <div class="modalCon" v-if="seeChannelFlag">
        <span>合同资料：</span>
        <div class="modalConSel htong">
          <em class="downBox" v-if="uploadFileList && uploadFileList.length">
            <i @click="fujianDown(item)" v-for="(item, index) in uploadFileList"
              :key="index">{{ item.name }}</i></em>
          <em class="downBox" v-else>暂无</em>
        </div>
      </div>
      <div class="modalCon" v-if="formFlag && formFlag2 && !seeChannelFlag">
        <span>合同资料：</span>
        <div class="modalConSel">
          <Tag v-for="(item, index) in uploadFileList" :key="index" closable
            @on-close="uploadFileListClose(index)">{{ item.name }}</Tag>
          <Upload style="margin-top: 5px" :disabled="seeChannelFlag" multiple :max-size="10240"
            :on-exceeded-size="handleMaxSize" :action="upload.reqUrl" ref="upload"
            name="multipartFile" :headers="upload.headers" :show-upload-list="false"
            :on-success="handleSuccess">
            <Button icon="ios-cloud-upload-outline" :disabled="seeChannelFlag"
              size="small">上传文件</Button>
          </Upload>
        </div>
      </div>
      <div class="modalCon" v-if="formFlag && formFlag2">
        <span>OA营销采购申请单：</span>
        <div class="modalConSel">
          <Input v-model="channelRelated.oaProcurement" :disabled="seeChannelFlag"
            placeholder="输入OA营销采购申请单：" />
        </div>
      </div>
      <div class="modalCon">
        <span><em>*</em> 渠道状态：</span>
        <div class="modalConSel">
          <RadioGroup v-model="channelRelated.channelStatus" @on-change="channelStatusChoose">
            <Radio label="1" :disabled="seeChannelFlag">启用</Radio>
            <Radio label="2" :disabled="seeChannelFlag">禁用</Radio>
          </RadioGroup>
        </div>
      </div>
      <div class="modalCon">
        <span>备注：</span>
        <div class="modalConSel">
          <Input v-model="channelRelated.remarks" :disabled="seeChannelFlag" type="textarea"
            :rows="4" :maxlength="300" placeholder="请输入备注..." />
        </div>
      </div>
      <div slot="footer">
        <div class="footDi">
          <Button @click="modalCancel">{{
            seeChannelFlag ? "关闭" : "取消"
          }}</Button>
          <Button type="primary" v-if="!seeChannelFlag" @click="modalOk">确定</Button>
        </div>
      </div>
    </Modal>
    <Modal v-model="modal1" :closable="false" :mask-closable="false">
      <p class="modal1Text">该渠道已有关联的客户，不可删除。</p>
      <div slot="footer" class="modal1Footer">
        <Button type="primary" @click="modal1Ok">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import toolApi from '@/biz/base/tool'
  import channelMgr from '@/biz/channel/channel'
  export default {
    data() {
      return {

        upload: toolApi.unloadFile(),

        seeChannelFlag: false,
        buildingId: this.$dt.buildInfo().housesId,
        formFlag: true,
        formFlag2: true,
        iscooperationType: false,
        channelRelated: {
          channelType: '3', //渠道类型
          channelName: '', //渠道名字
          cooperationType: '1', //合作类型
          startDate: '', //合作时间
          endDate: '',
          channelCostType: '', //渠道费用类型
          channelCost: null, //渠道费用
          oaProcurement: '', //营销清单
          channelStatus: '1',
          remarks: '', //备注
        },
        cooperationTypeList: [], //合作类型数据
        dataParams: {
          buildingId: this.$dt.buildInfo().housesId,
        },
        uploadFileList: [], //上传文件的
        create: false,
        onresizeHeight: 0, //tabl高
        modal: false, //新增弹框
        modal1: false,
        channelTypeData: this.$dt.dictInfo().channelType,
        channelCostTypeData: this.$dt.dictInfo().channelCostType,
        caseChannelId: '',
        userMess: JSON.parse(this.$tool.getStorage('userMess')),
        channelId: '',

        channelStatus: '1', //渠道状态

        pageData: {
          total: 0,
          current: 1,
          rows: 10,
          pageSizeOpts: [10, 20, 30, 40, 50],
        },
        columns: [
          {
            title: '序号',
            type: 'index',
            width: 100,
            align: 'center',
          },
          {
            title: '渠道分类',
            key: 'channelType',
            minWidth: 120,
            align: 'center',
            render: (h, params) => {
              return h(
                'div',
                this.$formatter.switchName('channelType', params.row.channelType)
              )
            },
          },
          {
            title: '渠道名称',
            key: 'channelName',
            minWidth: 120,
            align: 'center',
          },
          {
            title: '合作类型',
            key: 'cooperationTypeName',
            minWidth: 120,
            align: 'center',
          },
          {
            title: '合作日期',
            key: '',
            minWidth: 220,
            align: 'center',
            render: (h, params) => {
              return h(
                'div',
                !params.row.cooperationStartDate && !params.row.cooperationEndDate ?
                '' :
                `${
                    params.row.cooperationStartDate
                      ? params.row.cooperationStartDate
                      : ' - '
                  }至${
                    params.row.cooperationEndDate
                      ? params.row.cooperationEndDate
                      : ' - '
                  }`
              )
            },
          },
          {
            title: '渠道费用',
            key: 'channelName',
            minWidth: 120,
            align: 'center',
            render: (h, params) => {
              return h(
                'div',
                params.row.channelCostValue &&
                params.row.unit &&
                `${params.row.channelCostValue}${params.row.unit}`
              )
            },
          },
          {
            title: '操作时间',
            key: 'updateTime',
            width: 200,
            align: 'center',
            render: (h, params) => {
              return h('div', params.row.updateTime.substr(0, 16))
            },
          },
          {
            title: '操作人',
            key: 'updaterName',
            width: 200,
            align: 'center',
          },
          {
            title: '状态',
            key: 'validate',
            width: 200,
            align: 'center',
            render: (h, params) => {
              return h('div', params.row.validate == 1 ? '启用' : '禁用')
            },
          },

          {
            title: '操作',
            key: 'operation',
            width: 200,
            align: 'center',
            fixed: 'right',
            render: (h, params) => {
              return h('div', [
                h(
                  'a',
                  {
                    on: {
                      click: (e) => {
                        e.stopPropagation()
                        this.editChannel(params.row, 'see')
                      },
                    },
                  },
                  '查看'
                ),
                h(
                  'a',
                  {
                    style: {
                      marginLeft: '10px',
                      cursor: this.unlocking('0102010402') && params.row.dataSource !=
                        3 ?
                        'pointer' : 'not-allowed',
                      color: this.unlocking('0102010402') && params.row.dataSource !=
                        3 ?
                        '#2d8cf0' : '#c5c8ce',
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation()
                        this.unlocking('0102010402') &&
                          params.row.dataSource != 3 &&
                          this.editChannel(params.row, 'edit')
                      },
                    },
                  },
                  '编辑'
                ),
                h(
                  'a',
                  {
                    style: {
                      marginLeft: '10px',
                      cursor: this.unlocking('0102010403') && params.row.dataSource !=
                        3 ?
                        'pointer' : 'not-allowed',
                      color: this.unlocking('0102010403') && params.row.dataSource !=
                        3 ?
                        '#2d8cf0' : '#c5c8ce',
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation()
                        this.unlocking('0102010403') &&
                          params.row.dataSource != 3 &&
                          this.delChannel(params.row)
                      },
                    },
                  },
                  '删除'
                ),
              ])
            },
          },
        ],
        data: [],
      }
    },
    methods: {
      compareDate(date1, date2) {
        let oDate1 = new Date(date1)
        let oDate2 = new Date(date2)
        if (oDate1.getTime() < oDate2.getTime()) {
          return true
        } else {
          return false
        }
      },
      fujianDown(val) {
        toolApi.downloadFile(val.url, val.name)
      },
      // 校验费用
      checkChannelCost() {
        if (this.channelRelated.channelCost) {
          let reg = /^([0-9]+[\d]*(.[0-9]{1,2})?)$/
          if (!reg.test(this.channelRelated.channelCost)) {
            this.$Message.warning('请输入数字,最多保留两位小数')
            this.channelRelated.channelCost = null
          }
        }
      },
      uploadFileListClose(index) {
        this.uploadFileList.splice(index, 1)
      },

      handleMaxSize(file) {
        this.$Message.warning('最大支持10M。')
      },

      handleSuccess(res, file) {
        this.uploadFileList.push({
          url: res.data.imageURL,
          name: file.name,
        })
      },

      // 选择渠道类型
      channelTypeChange(val) {
        if (val == 2 || val == 3) {
          this.formFlag = true
          let cooperationType = this.channelTypeData.find((item) => {
            return item.key == val
          })
          this.cooperationTypeList = cooperationType.children
          this.channelRelated.cooperationType = '1'
          this.formFlag2 = true
        } else {
          this.formFlag = false
          this.channelRelated.cooperationType = ''
        }
      },
      // 选择合作类型
      cooperationTypeChange(val) {
        if (val == 1 || val == 3) {
          this.formFlag2 = true
        } else {
          this.formFlag2 = false
        }
      },
      modal1Ok() {
        this.modal1 = false
      },
      channelStatusChoose(val) {
        console.log(val, '状态更改')
      },
      //案场渠道列表
      reChannelList() {
        let params = {
          page: this.pageData.current,
          rows: this.pageData.rows,
          buildingId: this.buildingId,
        }
        channelMgr
          .caseChannelList(params)
          .then((res) => {
            this.data = res.list
            this.pageData.total = parseInt(res.total)
          })
          .catch((err) => {
            this.$Message.error(err)
          })
      },
      addChannel() {
        this.modal = true
        this.create = true
        this.seeChannelFlag = false
      },
      //渠道编辑
      editChannel(val, type) {
        console.log(val)
        if (type == 'see') {
          this.seeChannelFlag = true
        } else {
          this.seeChannelFlag = false
          val.cooperationType ?
            (this.iscooperationType = true) :
            (this.iscooperationType = false)
        }
        this.caseChannelId = val.channelId
        this.create = false
        this.modal = true
        let cooperationType = this.channelTypeData.find((item) => {
          return item.key == val.channelType
        })
        this.cooperationTypeList = cooperationType.children
        this.uploadFileList = JSON.parse(val.channelAnnex)
        this.channelRelated = {
          channelType: val.channelType ?
            String(val.channelType) : val.channelType,
          channelName: val.channelName,
          cooperationType: val.cooperationType ?
            String(val.cooperationType) : val.cooperationType,
          startDate: val.cooperationStartDate,
          endDate: val.cooperationEndDate,
          channelCostType: val.channelCostType,
          channelCost: val.channelCostValue,
          oaProcurement: val.oaProcurement,
          channelStatus: val.validate ? String(val.validate) : val.validate,
          remarks: val.comment,
        }
        if (val.cooperationType == 1 || val.cooperationType == 3) {
          this.formFlag2 = true
        } else {
          this.formFlag2 = false
        }
        if (val.channelType == 2 || val.channelType == 3) {
          this.formFlag = true
        } else {
          this.formFlag = false
        }
      },
      modalOk() {
        if (this.create) {
          this.reChannelCreate()
        } else {
          this.reChannelUpdate()
        }
      },
      //新增案场渠道
      reChannelCreate() {
        if (!this.channelRelated.channelName) {
          this.$Message.warning('请输入渠道名称。')
          return false
        }
        if (this.formFlag && this.formFlag2) {
          if (!this.channelRelated.startDate || !this.channelRelated.endDate) {
            this.$Message.warning('请选择合作日期。')
            return false
          } else {
            if (
              !this.compareDate(
                this.channelRelated.startDate,
                this.channelRelated.endDate
              )
            ) {
              this.$Message.warning('开始日期不能大于结束日期。')
              return false
            }
          }
          if (
            !this.channelRelated.channelCostType ||
            !this.channelRelated.channelCost
          ) {
            this.$Message.warning('请完成渠道费用。')
            return false
          }
        }

        if (!this.formFlag2) {
          if (
            this.channelRelated.startDate &&
            this.channelRelated.endDate &&
            !this.compareDate(
              this.channelRelated.startDate,
              this.channelRelated.endDate
            )
          ) {
            this.$Message.warning('开始日期不能大于结束日期。')
            return false
          }
        }

        let params = {
          buildingId: this.buildingId, //楼盘id
          channelAnnex: this.uploadFileList ?
            JSON.stringify(this.uploadFileList) : '[]', //渠道附件
          channelCostType: this.channelRelated.channelCostType, //渠道费用类型
          channelCostValue: this.channelRelated.channelCost, //	渠道费用值
          channelName: this.channelRelated.channelName, //	渠道名称
          channelType: this.channelRelated.channelType, //渠道分类
          comment: this.channelRelated.remarks, //备注
          cooperationEndDate: this.channelRelated.endDate, //合作结束时间
          cooperationStartDate: this.channelRelated.startDate, //合作开始时间
          cooperationType: this.channelRelated.cooperationType, //合作类型
          // dataSource: '', //1:渠道库  2:自定义 3:系统渠道---不传，控制是否可编辑
          oaProcurement: this.channelRelated.oaProcurement, //oa营销采购申请单
          unit: this.channelRelated.channelCostType == 1 ? '元' : '%', //单位
          validate: this.channelRelated.channelStatus, //是否有效(1:有效 2:无效)
        }
        channelMgr.caseChannelInsert(params).then((res) => {
          this.$Message.success('渠道新增成功。')
          this.reChannelList()
          this.modalCancel()
        })
      },
      //编辑渠道
      reChannelUpdate() {
        if (!this.channelRelated.channelName) {
          this.$Message.warning('请输入渠道名称。')
          return false
        }
        if (this.formFlag && this.formFlag2) {
          if (!this.channelRelated.startDate || !this.channelRelated.endDate) {
            this.$Message.warning('请选择合作日期。')
            return false
          } else {
            if (
              !this.compareDate(
                this.channelRelated.startDate,
                this.channelRelated.endDate
              )
            ) {
              this.$Message.warning('开始日期不能大于结束日期。')
              return false
            }
          }
          if (
            !this.channelRelated.channelCostType ||
            !this.channelRelated.channelCost
          ) {
            this.$Message.warning('请完成渠道费用。')
            return false
          }
        }
        if (!this.formFlag2) {
          if (
            this.channelRelated.startDate &&
            this.channelRelated.endDate &&
            !this.compareDate(
              this.channelRelated.startDate,
              this.channelRelated.endDate
            )
          ) {
            this.$Message.warning('开始日期不能大于结束日期。')
            return false
          }
        }

        let params = {
          channelId: this.caseChannelId,
          channelAnnex: this.uploadFileList ?
            JSON.stringify(this.uploadFileList) : '[]', //渠道附件
          channelCostType: this.channelRelated.channelCostType, //渠道费用类型
          channelCostValue: this.channelRelated.channelCost, //	渠道费用值
          cooperationType: this.channelRelated.cooperationType, //合作类型
          comment: this.channelRelated.remarks, //备注
          cooperationEndDate: this.channelRelated.endDate ?
            this.$tool.dateFtt('yyyy/MM/dd', this.channelRelated.endDate) : null, //合作结束时间
          cooperationStartDate: this.channelRelated.startDate ?
            this.$tool.dateFtt('yyyy/MM/dd', this.channelRelated.startDate) : null, //合作开始时间
          oaProcurement: this.channelRelated.oaProcurement, //oa营销采购申请单
          unit: this.channelRelated.channelCostType == 1 ? '元' : '%', //单位
          validate: this.channelRelated.channelStatus, //是否有效(1:有效 2:无效)
        }
        console.log(params)
        channelMgr.caseChannelUpdate(params).then((res) => {
          this.$Message.success('渠道更新成功。')
          this.reChannelList()
          this.modalCancel()
        })
      },
      delChannel(val) {
        this.$Modal.confirm({
          title: '提示',
          content: '<p> 是否该渠道删除？</p>',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            let params = {
              channelId: val.channelId,
            }
            channelMgr.caseChannelDelete(params).then((res) => {
              this.reChannelList()
              this.$Message.success('删除成功。')
            })
          },
        })
      },

      modalCancel() {
        this.modal = false
        this.formFlag = true
        this.formFlag2 = true
        this.uploadFileList = []
        let cooperationType = this.channelTypeData.find((item) => {
          return item.key == 3
        })
        this.cooperationTypeList = cooperationType.children
        this.channelRelated = {
          channelType: '3', //渠道类型
          channelName: '', //渠道名字
          cooperationType: '1', //合作类型
          startDate: '', //合作时间
          endDate: '',

          channelCostType: '', //渠道费用类型
          channelCost: null, //渠道费用
          oaProcurement: '', //营销清单
          channelStatus: '1',
          remarks: '', //备注
        }
      },
      startDateChange(val) {
        console.log(val, '删除')
        if (val) {
          this.channelRelated.startDate = val
        } else {
          this.channelRelated.startDate = ''
        }

        console.log(
          this.channelRelated.startDate,
          'this.channelRelated.startDate'
        )
      },
      endDateChange(val) {
        if (val) {
          this.channelRelated.endDate = val
        } else {
          this.channelRelated.endDate = ''
        }
      },
      channelCostTypeChange() {
        this.channelRelated.channelCost = null
      },
      pageOnChangeFun(page) {
        this.reChannelList()
      },
      pageOnPageSizeChangeFun(rows) {
        this.reChannelList()
      },
      initData() {
        this.$nextTick(() => {
          this.onresizeHeight =
            window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
        })
        this.reChannelList()
      },
    },
    created() {
      let cooperationType = this.channelTypeData.find((item) => {
        return item.key == 3
      })
      this.cooperationTypeList = cooperationType.children
      this.initData()
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight =
              window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 150
          }, 10)
        })()
      }
    },
  }
</script>
<style lang="scss" scoped>
  .channelConfig {
    .ivu-table-cell {
      padding: 0;
    }

    .ivu-table-cell-slot {
      &>.sp1:last-child {
        border: none;
      }
    }

    .allCustomersP {
      padding: 8px 14px;
    }

    .teamConfigBtn {
      margin: 10px 0;
      padding-left: 14px;
      display: flex;
      flex-direction: row;

      button {
        margin-right: 10px;
      }
    }

    .tab {
      margin: 10px 0;

      .sp1 {
        display: block;
        min-height: 48px;
        line-height: 48px;
        text-align: center;
        border-bottom: 1px #e8eaec solid;
      }
    }

    .firstColumns {
      padding-left: 20px;
    }

    .caoBtn {
      color: #2d8cf0;
      cursor: pointer;
      display: inline-block;
      padding: 0 5px;
    }
  }

  .modalCon {
    display: flex;
    flex-direction: row;
    margin-top: 20px;

    &>span {
      width: 140px;
      text-align: right;
      line-height: 30px;

      em {
        font-style: normal;
        color: red;
      }
    }

    .modalConSel {
      width: 300px;

      .nameSel {
        margin-top: 10px;
      }
    }

    .channelCostType {
      display: flex;
      flex-direction: row;

      >* {
        margin: 0 2px;
        line-height: 32px;
      }
    }
  }

  .tip {
    line-height: 2;
    color: #999;
    font-size: 12px;
    text-align: right;
    width: 420px;
  }

  .searchBox {
    flex: 1;
    display: flex;
    flex-direction: row;

    .caseSearch {
      display: flex;
      flex-direction: row;
    }
  }

  .iconBox {
    margin-top: 6px;
  }

  .IconAdd {
    vertical-align: -4px;
    cursor: pointer;
  }

  .iconDisable {
    font-size: 12px;
    color: #2d8cf0;
    margin: 0 10px;
    cursor: pointer;
  }

  .modal1Text {
    padding: 20px 0;
    text-align: center;
  }

  .modal1Footer {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .footDi {
    display: flex;
    flex-direction: row;
    justify-content: center;
  }

  .downBox {
    font-style: normal;
    line-height: 32px;

    >i {
      color: #2d8cf0;
      display: block;
      font-style: normal;
      cursor: pointer;
    }
  }
</style>